新手紀錄一下學習 SQL 的過程
使用 XAMPP 內的 phpMyAdmin 作為練習平台
此篇記載 如何 增刪改查資料
如有錯,歡迎提出,新手初學
SELECT * FROM `users`
DELETE FROM `users` WHERE `id`='6'
UPDATE `users` SET `age`=47 WHERE `id` = '1';
-- AS 取別名
-- 原本欄位為 first_name 改為 forename (僅修改顯示結果的欄位名)
SELECT first_name AS forename FROM `users`
INSERT INTO users(name,password,is_admin,register_date)
VALUES('Mark','46',1,now());
-- 注意欄位名字 & 數量必須符合
INSERT INTO users(name,password,is_admin)
VALUES('Mark','46',1),('Tim','47',0);
SELECT * -- 欄位名 column_name
FROM `users` -- 資料表名 table_name
WHERE `age` > 47 -- 判斷式 condition
LIMIT 5; -- 顯示筆數 number
OFFSET 5; -- 取 5 ~ 10筆資料
BETWEEN 20 AND 30; -- 其數值在 20 & 30 之間
SELECT * FROM `users` WHERE `name`='Mark' AND `age`<30;
SELECT * FROM `users` WHERE `name` ='張三' OR `age`>24;
-- 排除 張三
SELECT * FROM `users` WHERE NOT `name`='張三';
-- 取得 Tim Carter & Mark Carter
SELECT * FROM Persons
WHERE (FirstName='Tim' OR FirstName='Mark')
AND LastName='Carter'
-- 選出不重複的年齡且大於30,並統計各年齡的人數
SELECT age, COUNT(age) FROM `users` WHERE `age`>30 GROUP BY age
-- 選出不重複的地區,並統計出各區域居住的 user 數量
SELECT location, COUNT(location) FROM `users` GROUP BY location
SELECT DISTINCT `name` FROM users;
-- IN 多個關鍵字查詢
SELECT * FROM `users` WHERE `job` IN ('sales','design')
-- 選出內容有包含關鍵字的文章
SELECT * FROM `posts` WHERE `article` LIKE '%關鍵字%'
-- 選出並非 M 開頭的名字
SELECT * FROM `users` WHERE `name` NOT LIKE 'M%'
-- 表 A 開頭 Z 結尾 且中間有一個字母的字串
-- ABZ 符合 AOOZ 不符合 (中間必須只有一個字母)
SELECT * FROM `posts` WHERE `article` LIKE 'A_Z'
SELECT * FROM `users` ORDER BY `id` DESC
-- 先排序 first_name 後排序 last_name
SELECT * FROM `users`
ORDER BY first_name, last_name;
SELECT COUNT(id) FROM comment;
SELECT MAX(age) FROM users;
SELECT MIN(age) FROM users;
SELECT SUM(age) FROM users;
SELECT AVG(age) FROM users;
SELECT UCASE(first_name), LCASE(last_name) FROM users;